package org.jflame.devAide.service;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.lang3.SystemUtils;
import org.jflame.devAide.AppContext;
import org.jflame.devAide.util.UIUtils;

/**
 * 文件相关功能服务
 * 
 * @author charles.zhang
 */
public final class FileService {

    final static String CFG_FILE_NAME = ".cfg.properties";
    final static String DATA_DIR_NAME = ".devAide";

    public static void initDataFile() throws IOException {
        File userDir = SystemUtils.getUserDir();
        AppContext.DATA_DIR = userDir.toPath()
                .resolve(DATA_DIR_NAME);

        if (!Files.exists(AppContext.DATA_DIR)) {
            Files.createDirectory(AppContext.DATA_DIR);
        }
        AppContext.CFG_FILE = AppContext.DATA_DIR.resolve(CFG_FILE_NAME);
        if (!Files.exists(AppContext.CFG_FILE)) {
            Files.createFile(AppContext.CFG_FILE);
        }
    }

    public static void initBaseDir() {
        String baseDir = System.getProperty("baseDir");
        // 获取项目当前的文件夹路径
        if (baseDir == null) {
            baseDir = Paths.get(URI.create(AppContext.hostServices()
                    .getDocumentBase()))
                    .toString();

            // 获取运行时jar包的文件夹路径，如果是在ide中直接运行，此时没有打包，将会返回空字符串
            // String codeBase = hostServices.getCodeBase();
            // String uri = hostServices.resolveURI(documentBase, "logo.png");
        }
        AppContext.BASE_DIR = Paths.get(baseDir);
    }

    /**
     * 在数据文件夹下创建
     * 
     * @param dir
     */
    public static Path createDataDir(String dir) {
        Path newPath = AppContext.DATA_DIR.resolve(dir);
        if (Files.notExists(newPath)) {
            try {
                Files.createDirectories(newPath);
                newPath.toFile()
                        .setWritable(true);
            } catch (IOException e) {
                UIUtils.showException("无法创建目录" + newPath, e);
            }
        }
        return newPath;
    }

    public static String readText(Path file, boolean isCreateIfNotExist) throws IOException {
        if (!Files.exists(file)) {
            if (isCreateIfNotExist) {
                Files.createFile(file);
            }
            return null;
        } else {
            return Files.readString(file);
        }
    }
}
